import React, { Fragment, useState, useEffect, useCallback, useMemo, memo } from 'react';
import { connect } from 'react-redux'
import { actions } from './module'
/**
 * input button
 * list列表
 * 状态展示
 * button
 * 
 * // 
 * Todolist
 * totos:  totoItem
 * 
 * 优化：
 * 1. memo优化：子组件
 * 2. useCallback 优化：传入子组件的方法
 * 3. 
 * 
 */

interface CProps {
  value: string;
  changeInputVal: (e: any) => void;
  addToto: () => void
}

const Control: React.FC<CProps> = memo((props: any) => {
  const { value, changeInputVal, addToto } = props
  return (
    <Fragment>
      <input type="text" value={value} onChange={changeInputVal} />
      <button onClick={addToto}>提交</button>
    </Fragment>
  )
})

interface LProps {
  list: any[];
  removeTodo: (id: number) => void
}

const Todos: React.FC<LProps> = memo((props: any) => {
  const { list, removeTodo } = props
  return (<ul>
    {
      list.map((item: any, index: number) => {
        return <li key={index} onClick={() => removeTodo(index)}>
          {item}
        </li>
      })
    }
  </ul>)
})

interface TProps {
  value: string,
  list: any[],
  dispatch: any
}

const Todolist: React.FC<TProps> = (props: any) => {
  const {
    dispatch,
    value,
    list
  } = props

  // changeValue方法
  const changeInputVal = useCallback((e: any) => {
    dispatch(actions.changeInputValue(e.target.value))
  }, [value])

  // 添加方法
  const addToto = useCallback(() => {
    dispatch(actions.addTodo())
  }, [])

  // 删除方法
  const removeTodo = useCallback((id: any) => {
    dispatch(actions.removeTodo(id))
  }, [])

  return <div>
    <Control
      value={value}
      addToto={addToto}
      changeInputVal={changeInputVal}
    />

    {/* 一个函数如果默认传入子组件，需要性能优化 useCallback */}
    <Todos
      list={list}
      removeTodo={(index) => removeTodo(index)} // 
    />
  </div>
}

export default connect((state: any) => {
  // console.log(state, 'state')
  return { ...state.todo }
}, (dispatch) => {
  return { dispatch }
})(Todolist)